package com.mars.controller;

import com.mars.po.Product;
import com.mars.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.ServerErrorException;

@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index(@ModelAttribute("product") Product product, Model model) {
        if (product.getId() != null || product.getName() != null || product.getPrice() != null) {
            model.addAttribute("query", product);
            model.addAttribute("products", this.productService.findAllByPo(product));
        } else {
            model.addAttribute("products", this.productService.findAll());
        }
        return "product/index";
    }

    @RequestMapping(value = "/view",method = RequestMethod.GET)
    public String view(int id,Model model) {
        model.addAttribute("product",productService.findOne(id));
        return "product/view";
    }

    @RequestMapping(value = "/update",produces= MediaType.TEXT_PLAIN_VALUE)
    public String update(HttpServletRequest request, Model model, @ModelAttribute("product") Product product) {

        if (request.getMethod().equals("GET")) {
            model.addAttribute("product", productService.findOne(product.getId()));
            return "product/update";
        } else if (request.getMethod().equals("POST")) {
            if (productService.update(product) <= 0){
                model.addAttribute("error","修改失败");
            }
        }
        return "redirect:view?id="+product.getId().toString();
    }

    @RequestMapping("/create")
    public String create( HttpServletRequest  request,Model model,@ModelAttribute("product")Product product) {
        if (request.getMethod().equals("POST")) {
            Integer id = productService.insert(product);
            if (id<=0){
                model.addAttribute("error","新建商品失败");
            }
            return "redirect:index";
        }
        return "product/create";
    }

    @RequestMapping("/delete")
    public String delete(int id,Model model){
        if (productService.deleteById(id) <= 0){
            model.addAttribute("error","删除失败");
        }
        return "redirect:index";
    }


}
